package org.truenewx.tnxjee.core.enums;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.truenewx.tnxjee.core.enums.support.EnumItemValueHelper;
import org.truenewx.tnxjee.core.util.ClassUtil;

/**
 * 枚举常量项解决器
 */
public class EnumConstantItemResolver implements EnumItemResolver<Enum<?>> {

    public static final int ORDER = 0;

    @Override
    public int getOrder() {
        return ORDER;
    }

    @Override
    public String getKey(Enum<?> enumConstant) {
        return enumConstant.name();
    }

    @Override
    public String getValue(Enum<?> enumConstant) {
        return EnumItemValueHelper.getValue(enumConstant);
    }

    @Override
    public Map<String, Object> getAttachment(Enum<?> enumConstant) {
        Map<String, Object> attachment = new HashMap<>();
        ClassUtil.loopSimplePropertyDescriptors(enumConstant.getClass(), null, pd -> {
            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                String propertyName = pd.getName();
                // 忽略枚举常量中的name和ordinal
                if (propertyName.equals("name") || propertyName.equals("ordinal")) {
                    return;
                }
                JsonIgnore jsonIgnore = readMethod.getAnnotation(JsonIgnore.class);
                if (jsonIgnore != null && jsonIgnore.value()) {
                    return;
                }
                try {
                    Object attachedFieldValue = readMethod.invoke(enumConstant);
                    if (attachedFieldValue != null) {
                        attachment.put(propertyName, attachedFieldValue);
                    }
                } catch (Exception ignored) {
                }
            }
        });
        return attachment;
    }
}
